package com.huluobo.a2107jetpackkotlindemo.coroutine

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.lifecycleScope
import com.google.gson.Gson
import com.huluobo.a2107jetpackkotlindemo.R
import com.huluobo.a2107jetpackkotlindemo.databinding.ActivityRetrofitBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create

class RetrofitActivity : AppCompatActivity() {

    private lateinit var activityRetrofitBinding: ActivityRetrofitBinding

    private val retrofit = Retrofit.Builder().baseUrl("http://10.161.9.80:7012")
        .addConverterFactory(GsonConverterFactory.create()).build()

    private val apiService = retrofit.create(ApiService::class.java)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityRetrofitBinding = ActivityRetrofitBinding.inflate(layoutInflater)
        setContentView(activityRetrofitBinding.root)

//        apiService.queryData(0, 1, 10).enqueue(object : Callback<GoodsBeanResult> {
//            override fun onResponse(call: Call<GoodsBeanResult>, response: Response<GoodsBeanResult>) {
//                activityRetrofitBinding.tvText.text = Gson().toJson(response.body())
//            }
//
//            override fun onFailure(call: Call<GoodsBeanResult>, t: Throwable) {
//                activityRetrofitBinding.tvText.text = t.message
//            }
//        })
        //如果retrofit2.8以下 不支持直接在main线程中调用,需要线程使用
//        val job = Job()
//        CoroutineScope(job).launch(Dispatchers.Main) {
//            val result = withContext(Dispatchers.IO) {
//                apiService.queryData2(0, 1, 10)
//            }
//            activityRetrofitBinding.tvText.text = Gson().toJson(result)
//        }

        //retrofit2.9以上可以不切换线程使用
        val job = Job()
        CoroutineScope(job).launch(Dispatchers.Main) {
            val result = apiService.queryData2(0, 1, 10)
            activityRetrofitBinding.tvText.text = Gson().toJson(result)
        }

        lifecycleScope.launchWhenStarted {
            Log.i("TagA", "launchWhenStarted")
        }
        lifecycleScope.launchWhenCreated {
            Log.i("TagA", "launchWhenCreated")
        }

        lifecycleScope.launchWhenResumed {
            Log.i("TagA", "launchWhenResumed")
        }

    }
}